
 <!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  
    <title>玩转Angular1(7)--异步提交表单（文件）服务 | Here. There.</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3, minimum-scale=1">
    
    <meta name="author" content="被删">
    
    <meta name="description" content="AngularJS(v1.5.8)已经成为项目们的基本框架，《玩转Angular1》系列用于记录项目中的一些好玩或者比较特别的思路。本文记录在angular中封装上传本地图片服务，以及异步提交表单（包括图片）服务的过程。">
    
    
    
    
    <link rel="alternate" href="/atom.xml" title="Here. There." type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/pacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/pacman.jpg">
    
    <link rel="stylesheet" href="/css/style.css">
    
<script type="text/javascript">
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?3d902de4a19cf2bf179534ffd2dd7b7f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</head>

  <body>
    <header>
      <div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/sun.png" alt="Here. There." title="Here. There."/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Here. There.">Here. There.</a></h1>
				<h2 class="blog-motto">Love ice cream. Love sunshine. Love life. Love the world. Love myself. Love you.</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="菜单">
			</a></div>
			<nav class="animated">
				<ul>
					
						<li><a href="/">首页</a></li>
					
						<li><a href="https://github.com/godbasin/godbasin.github.io">所有文章</a></li>
					
						<li><a href="/archives">归档</a></li>
					
						<li><a href="/categories">分类</a></li>
					
						<li><a href="/about">关于我</a></li>
					
				</ul>
			</nav>			
</div>

    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2017/02/26/angular-free-7-async-form-submit/" title="玩转Angular1(7)--异步提交表单（文件）服务" itemprop="url">玩转Angular1(7)--异步提交表单（文件）服务</a>
  </h1>
  <p class="article-author">By
    
      <a href="https://godbasin.github.io" title="被删">被删</a>
    </p>
  <p class="article-time">
    <time datetime="2017-02-26T01:17:13.000Z" itemprop="datePublished">2017-02-26</time>
    更新日期:<time datetime="2018-12-18T15:26:32.545Z" itemprop="dateModified">2018-12-18</time>
    
  </p>
</header>
	<div class="article-content">
		
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">文章目录</strong>
		<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#上传本地图片"><span class="toc-number">1.</span> <span class="toc-text">上传本地图片</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#添加OpenImageDialog函数"><span class="toc-number">1.1.</span> <span class="toc-text">添加OpenImageDialog函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在创建账户中使用该服务"><span class="toc-number">1.2.</span> <span class="toc-text">在创建账户中使用该服务</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#异步表单提交"><span class="toc-number">2.</span> <span class="toc-text">异步表单提交</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AsyncForm服务"><span class="toc-number">2.1.</span> <span class="toc-text">AsyncForm服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配合OpenImageDialog服务使用"><span class="toc-number">2.2.</span> <span class="toc-text">配合OpenImageDialog服务使用</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结束语"><span class="toc-number">3.</span> <span class="toc-text">结束语</span></a></li></ol>
		</div>
		
		<p>AngularJS(v1.5.8)已经成为项目们的基本框架，《玩转Angular1》系列用于记录项目中的一些好玩或者比较特别的思路。<br>本文记录在angular中封装上传本地图片服务，以及异步提交表单（包括图片）服务的过程。<br><a id="more"></a></p>
<h2 id="上传本地图片"><a href="#上传本地图片" class="headerlink" title="上传本地图片"></a>上传本地图片</h2><hr>
<h3 id="添加OpenImageDialog函数"><a href="#添加OpenImageDialog函数" class="headerlink" title="添加OpenImageDialog函数"></a>添加OpenImageDialog函数</h3><p>我们在<code>app/shared/services</code>文件夹下新建<code>OpenImageDialog.ts</code>文件。<br>这里我们只创建最简单的功能，如打开图片对话框，并只接受一张图片上传，该函数返回一个Promise，其中resolve可获取参数包括：</p>
<ul>
<li>file: 上传文件</li>
<li>url: 图片url，可用于展示</li>
<li>name: 图片名字，从文件中获取</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// OpenImageDialog.ts</span></div><div class="line"><span class="comment">// 打开图片对话框，只接受一张图片上传</span></div><div class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">OpenImageDialog</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="comment">// 新建input，作为文件获取</span></div><div class="line">    <span class="keyword">const</span> input = <span class="built_in">document</span>.createElement(<span class="string">'input'</span>);</div><div class="line">    input.type = <span class="string">'file'</span>;</div><div class="line">    input.name = <span class="string">'file'</span>;</div><div class="line">    input.accept = <span class="string">'image/*'</span>;</div><div class="line">    <span class="keyword">let</span> resolve;</div><div class="line"></div><div class="line">    <span class="comment">// 新建Promise，并获取resolve函数</span></div><div class="line">    <span class="keyword">const</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">res, rej</span>) =&gt;</span> &#123;</div><div class="line">        resolve = res;</div><div class="line">    &#125;);</div><div class="line"></div><div class="line">    <span class="comment">// 设置input中图片改变时触发事件</span></div><div class="line">    input.onchange = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</div><div class="line">        <span class="comment">// 创建fileReader读取文件内容</span></div><div class="line">        <span class="keyword">const</span> fileReader = <span class="keyword">new</span> FileReader();</div><div class="line">        <span class="keyword">const</span> file = input.files[<span class="number">0</span>];</div><div class="line"></div><div class="line">        <span class="comment">// 读取完毕后，传入文件、图片信息以及名字</span></div><div class="line">        fileReader.onload = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</div><div class="line">            resolve(&#123; file, <span class="attr">url</span>: fileReader.result, <span class="attr">name</span>: input.value.substring(input.value.lastIndexOf(<span class="string">'\\'</span>) + <span class="number">1</span>) &#125;);</div><div class="line">        &#125;;</div><div class="line">        fileReader.readAsDataURL(file);</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    <span class="comment">// 触发表单点击事件</span></div><div class="line">    input.click();</div><div class="line"></div><div class="line">    <span class="comment">// 返回promise</span></div><div class="line">    <span class="keyword">return</span> promise;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="在创建账户中使用该服务"><a href="#在创建账户中使用该服务" class="headerlink" title="在创建账户中使用该服务"></a>在创建账户中使用该服务</h3><p>上一节中，我们创建了一些相关路由以及视图，其中包括一个创建账户模块，这里我们在该模块中添加点击上传图片按钮，并展示图片以及名字。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!--accountAdd.template.html--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">a</span> <span class="attr">class</span>=<span class="string">"btn btn-default"</span> <span class="attr">ng-click</span>=<span class="string">"VM.openImageDialog()"</span>&gt;</span>点击上传图片<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!--展示上传图片以及名字--&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-repeat</span>=<span class="string">"image in VM.images"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">img</span> <span class="attr">ng-src</span>=<span class="string">"&#123;&#123; image.url &#125;&#125;"</span> /&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; image.name &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<p>然后我们添加文件<code>accountAdd.controller.ts</code>，并创建一个控制器AccountAddCtrl：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// accountAdd.controller.ts</span></div><div class="line"><span class="keyword">import</span> &#123; OpenImageDialog &#125; <span class="keyword">from</span> <span class="string">'../../../shared/services/OpenImageDialog'</span>;</div><div class="line"><span class="keyword">const</span> angular = <span class="built_in">require</span>(<span class="string">'angular'</span>);</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">AccountAddCtrl</span> </span>&#123;</div><div class="line">    <span class="comment">// 获取依赖</span></div><div class="line">    public <span class="keyword">static</span> $inject = [</div><div class="line">        <span class="string">'$scope'</span></div><div class="line">    ];</div><div class="line">    images: any[] = [];</div><div class="line"></div><div class="line">    <span class="comment">// 注入依赖</span></div><div class="line">    <span class="keyword">constructor</span>(</div><div class="line">        private $scope</div><div class="line">    ) &#123;</div><div class="line">        <span class="comment">// VM用于绑定模板相关内容</span></div><div class="line">        $scope.VM = <span class="keyword">this</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 点击打开选择文件对话框</span></div><div class="line">    openImageDialog() &#123;</div><div class="line">        <span class="comment">// 调用openImageDialog，返回Promise，传入file、name、url参数</span></div><div class="line">        OpenImageDialog().then(<span class="function">(<span class="params">&#123;file, url, name&#125;</span>) =&gt;</span> &#123;</div><div class="line">            <span class="comment">// 添加进数组</span></div><div class="line">            <span class="keyword">this</span>.images.push(&#123; url, name &#125;);</div><div class="line">            <span class="comment">// 需手动刷新数据</span></div><div class="line">            <span class="keyword">this</span>.$scope.$digest();</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">export</span> <span class="keyword">default</span> (ngModule) =&gt; &#123;</div><div class="line">    ngModule.controller(<span class="string">'AccountAddCtrl'</span>, AccountAddCtrl);</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>最后，我们注册控制器，并在路由中关联模板和控制器。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// bootstrap.ts</span></div><div class="line"><span class="keyword">import</span> AccountAddCtrl <span class="keyword">from</span> <span class="string">'./modules/home/account/accountAdd.controller'</span>;</div><div class="line">[</div><div class="line">    ...</div><div class="line">    AccountAddCtrl</div><div class="line">].forEach(<span class="function">(<span class="params">service</span>) =&gt;</span> service(ngModule));</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// app.ts</span></div><div class="line">...</div><div class="line">&#123;</div><div class="line">    <span class="attr">name</span>: <span class="string">'home.accountsadd'</span>,</div><div class="line">    <span class="attr">url</span>: <span class="string">'/accountsadd'</span>,</div><div class="line">    <span class="attr">templateUrl</span>: <span class="string">'./modules/home/account/accountAdd.template.html'</span>,</div><div class="line">    <span class="attr">controller</span>: <span class="string">'AccountAddCtrl'</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>效果如图：<br><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/1485080178%281%29.png" alt="image"></p>
<h2 id="异步表单提交"><a href="#异步表单提交" class="headerlink" title="异步表单提交"></a>异步表单提交</h2><hr>
<h3 id="AsyncForm服务"><a href="#AsyncForm服务" class="headerlink" title="AsyncForm服务"></a>AsyncForm服务</h3><p>我们在这里创建个服务，用于异步提交表单，这里我们需要注入前面提到的qHttp服务。<br>该组件是方便与OpenImageDialog服一起使用，由于需要注入angular服务，所以我们需要在ngModele中进行注册，而OpenImageDialog服务则不需要。</p>
<p>AsyncForm服务调用时，可传入对象：</p>
<ul>
<li>files: 传入file input的dom对象</li>
<li>url: 服务器地址</li>
<li>params: 其他需要发送的参数{键：值}</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">AsyncForm</span> </span>&#123;</div><div class="line">    url: string;</div><div class="line">    qHttp: TODO;</div><div class="line">    contentType: TODO;</div><div class="line">    formData: TODO;</div><div class="line"></div><div class="line">    <span class="comment">// 注入qHttp服务</span></div><div class="line">    <span class="keyword">constructor</span>(qHttp, &#123; url, params, files = [], contentType &#125;) &#123;</div><div class="line">        <span class="comment">// 初始化参数</span></div><div class="line">        <span class="keyword">this</span>.qHttp = qHttp;</div><div class="line">        <span class="keyword">this</span>.url = url;</div><div class="line">        <span class="keyword">this</span>.contentType = contentType;</div><div class="line"></div><div class="line">        <span class="keyword">const</span> formData = <span class="keyword">new</span> FormData();</div><div class="line">        <span class="keyword">this</span>.formData = formData;</div><div class="line">        <span class="comment">// 若有传入文件，则添加</span></div><div class="line">        <span class="keyword">if</span> (files) &#123;</div><div class="line">            <span class="built_in">Array</span>.prototype.forEach.call(files, file =&gt; &#123;</div><div class="line">                formData.append(<span class="string">'file'</span>, file);</div><div class="line">            &#125;);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 若有其他参数，则添加</span></div><div class="line">        <span class="built_in">Object</span>.keys(params).forEach(<span class="function"><span class="params">key</span> =&gt;</span> &#123;</div><div class="line">            <span class="keyword">if</span> (params[key] != <span class="literal">null</span>) &#123;</div><div class="line">                formData.append(key, params[key]);</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    submit() &#123;</div><div class="line">        <span class="comment">// 提交，返回promise</span></div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.qHttp.post(<span class="keyword">this</span>.url, <span class="keyword">this</span>.formData, &#123;</div><div class="line">            <span class="attr">withCredentials</span>: <span class="literal">true</span>,</div><div class="line">            <span class="attr">headers</span>: &#123;</div><div class="line">                <span class="string">'Content-Type'</span>: <span class="literal">undefined</span></div><div class="line">            &#125;,</div><div class="line">            <span class="attr">transformRequest</span>: <span class="function"><span class="params">x</span> =&gt;</span> x</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">export</span> <span class="keyword">default</span> (ngModule) =&gt; &#123;</div><div class="line">    <span class="comment">// 注入qHttp服务</span></div><div class="line">    ngModule.factory(<span class="string">'AsyncForm'</span>, [<span class="string">'qHttp'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">qHttp</span>) </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="function"><span class="params">config</span> =&gt;</span> <span class="keyword">new</span> AsyncForm(qHttp, config).submit();</div><div class="line">    &#125;]);</div><div class="line"></div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>当然我们还需要在<code>bootstrap.ts</code>文件中注册该服务，这里就不详细讲解啦。</p>
<h3 id="配合OpenImageDialog服务使用"><a href="#配合OpenImageDialog服务使用" class="headerlink" title="配合OpenImageDialog服务使用"></a>配合OpenImageDialog服务使用</h3><p>AsyncForm服务配合OpenImageDialog服务使用，可实现较连贯的图片上传，或者异步表单提交。<br>这里我们在上面上传图片后，调用AsyncForm服务进行表单提交，当然我们还需要注入该服务：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// accountAdd.controller.ts</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">AccountAddCtrl</span> </span>&#123;</div><div class="line">    public <span class="keyword">static</span> $inject = [</div><div class="line">        ...</div><div class="line">        <span class="string">'AsyncForm'</span></div><div class="line">    ];</div><div class="line">    ...</div><div class="line"></div><div class="line">    constructor(</div><div class="line">        ...</div><div class="line">        private AsyncForm</div><div class="line">    ) &#123;...&#125;</div><div class="line"></div><div class="line">    <span class="comment">// 点击打开选择文件对话框</span></div><div class="line">    openImageDialog() &#123;</div><div class="line">        <span class="comment">// 调用openImageDialog，返回Promise，传入file、name、url参数</span></div><div class="line">        OpenImageDialog().then(<span class="function">(<span class="params">&#123;file, url, name&#125;</span>) =&gt;</span> &#123;</div><div class="line">            <span class="comment">// 添加进数组</span></div><div class="line">            <span class="keyword">this</span>.images.push(&#123; url, name &#125;);</div><div class="line">            <span class="comment">// 需手动刷新数据</span></div><div class="line">            <span class="keyword">this</span>.$scope.$digest();</div><div class="line">            <span class="comment">// 进行异步表单上传</span></div><div class="line">            <span class="keyword">this</span>.AsyncForm(&#123;</div><div class="line">                <span class="attr">files</span>: [file],</div><div class="line">                <span class="attr">url</span>: <span class="string">'http://modifyDetail'</span>,</div><div class="line">                <span class="attr">params</span>: &#123;</div><div class="line">                    <span class="attr">gender</span>: <span class="string">'male'</span></div><div class="line">                &#125;</div><div class="line">            &#125;).then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;<span class="built_in">console</span>.log(<span class="string">'success'</span>)&#125;, () =&gt;&#123;<span class="built_in">console</span>.log(<span class="string">'error'</span>)&#125;)</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>效果如图：<br><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/1485080798%281%29.png" alt="image"></p>
<p>这样，我们就实现了在angular中封装图片上传，并经过$http服务进行异步表单提交的功能了。</p>
<h2 id="结束语"><a href="#结束语" class="headerlink" title="结束语"></a>结束语</h2><hr>
<p>这节主要简单介绍了在angular中封装上传本地图片服务，以及异步提交表单（包括图片）服务的过程。当然，大家也可以在这个基础上进行拓展，把服务灵活处理，接受图片或者其他文件，单个或者多个文件，等等功能。<br><a href="https://github.com/godbasin/godbasin.github.io/tree/blog-codes/angular-free/7-async-form-submit" target="_blank" rel="external">此处查看项目代码</a><br><a href="http://angular-free.godbasin.com/angular-free-7-async-form-submit/index.html#/home/accountsadd" target="_blank" rel="external">此处查看页面效果</a></p>
  
		
		<p style="margin-top:50px;">查看Github有更多内容噢：<a href="https://github.com/godbasin">https://github.com/godbasin</a></p>
	</div>
	<img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/2code2.jpg" width="200" height="200" style="display:block;margin: 0 auto;" />
	<p style="text-align: center;margin-top: 10px;margin-bottom: 20px;">码生艰难，写文不易，给我家猪囤点猫粮了喵~</p>
	<div class="author-right">
  		<p>作者：被删</p>
  		<p>出处：<a href="https://godbasin.github.io">https://godbasin.github.io</a></p>
  		<p>本文版权归作者所有，欢迎转载，但未经作者同意必须保留此段声明，且在文章页面明显位置给出原文连接，否则保留追究法律责任的权利。</p>
	</div>
		<footer class="article-footer clearfix">

  <div class="article-tags">
  
  <span></span> <a href="/tags/笔记/">笔记</a>
  </div>


<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/angular混搭/">angular混搭</a>
</div>



<div class="article-share" id="share">

  
<!-- JiaThis Button BEGIN -->
<div class="jiathis_style_24x24">
	<a class="jiathis_button_qzone"></a>
	<a class="jiathis_button_tsina"></a>
	<a class="jiathis_button_tqq"></a>
	<a class="jiathis_button_weixin"></a>
	<a class="jiathis_button_renren"></a>
	<a href="http://www.jiathis.com/share?uid=2134021" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
</div>
<script type="text/javascript">
var jiathis_config = {data_track_clickback:'true'};
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code_mini/jia.js?uid=2134021" charset="utf-8"></script>
<!-- JiaThis Button END -->   


</div>
</footer>   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2017/03/04/angular-free-8-q-service-and-async-await/" title="玩转Angular1(8)--$q.all与async/await">
  <strong>PREVIOUS:</strong><br/>
  <span>
  玩转Angular1(8)--$q.all与async/await</span>
</a>
</div>


<div class="next">
<a href="/2017/02/25/angular-free-6-ui-router-in-angular/"  title="玩转Angular1(6)--ui-router与嵌套路由">
 <strong>NEXT:</strong><br/> 
 <span>玩转Angular1(6)--ui-router与嵌套路由
</span>
</a>
</div>

</nav>

	<!-- 如果不是首页且没使用 `comments: false` 关闭评论，则尝试加载评论 -->

    <!-- 配置中启用多说时，导入相应代码 -->
    


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="显示侧边栏"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">文章目录</strong>
  <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#上传本地图片"><span class="toc-number">1.</span> <span class="toc-text">上传本地图片</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#添加OpenImageDialog函数"><span class="toc-number">1.1.</span> <span class="toc-text">添加OpenImageDialog函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在创建账户中使用该服务"><span class="toc-number">1.2.</span> <span class="toc-text">在创建账户中使用该服务</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#异步表单提交"><span class="toc-number">2.</span> <span class="toc-text">异步表单提交</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AsyncForm服务"><span class="toc-number">2.1.</span> <span class="toc-text">AsyncForm服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配合OpenImageDialog服务使用"><span class="toc-number">2.2.</span> <span class="toc-text">配合OpenImageDialog服务使用</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结束语"><span class="toc-number">3.</span> <span class="toc-text">结束语</span></a></li></ol>
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="隐藏侧边栏"></a></div>
<aside class="clearfix">

  	
	<div class="archiveslist">
		<p class="asidetitle">最近文章</p>
			<ul class="archive-list">
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/07/11/vue-for-everyone-2/" title="9102全员学Vue--2.怎么三两下拼出一个页面">9102全员学Vue--2.怎么三两...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/30/about-front-end-2-principle/" title="前端这几年--2.工作原则和选择">前端这几年--2.工作原则和选择...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/27/vue-for-everyone-1/" title="9102全员学Vue--1.如何理解前端和Vue">9102全员学Vue--1.如何理解...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/17/wxapp-latest-20190617/" title="小程序开发月刊第六期（20190617）">小程序开发月刊第六期（2019061...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/17/wxapp-generate/" title="小程序的诞生">小程序的诞生</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/05/15/wxapp-latest-20190515/" title="小程序开发月刊第五期（20190515）">小程序开发月刊第五期（2019051...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/04/15/wxapp-latest-20190415/" title="小程序开发月刊第四期（20190415）">小程序开发月刊第四期（2019041...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/04/13/about-front-end-1-begin-in/" title="前端这几年--1.转岗之路">前端这几年--1.转岗之路...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/03/15/wxapp-latest-20190315/" title="小程序开发月刊第三期（20190315）">小程序开发月刊第三期（2019031...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/03/10/work-2-article/" title="写文章这件事">写文章这件事</a>
				</li>
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
			</ul>
	</div>


  
  <div class="archiveslist">
    <p class="asidetitle"><a href="/archives">归档</a></p>
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">七月 2019</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">六月 2019</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/05/">五月 2019</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">四月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">三月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/02/">二月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/01/">一月 2019</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/12/">十二月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">十一月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">十月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/09/">九月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/08/">八月 2018</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/07/">七月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/06/">六月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">五月 2018</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">二月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">10</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">15</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/03/">三月 2017</a><span class="archive-list-count">10</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/02/">二月 2017</a><span class="archive-list-count">41</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/01/">一月 2017</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/12/">十二月 2016</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/11/">十一月 2016</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/10/">十月 2016</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/09/">九月 2016</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/08/">八月 2016</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/07/">七月 2016</a><span class="archive-list-count">14</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/06/">六月 2016</a><span class="archive-list-count">9</span></li></ul>
  </div>


  
<div class="archiveslist">
	<p class="asidetitle"><a href="/categories">分类</a></p>
		<ul class="archive-list">
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/CSS炒饭/" title="CSS炒饭">CSS炒饭<sup>3</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/D3小馒头/" title="D3小馒头">D3小馒头<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/angular2火锅/" title="angular2火锅">angular2火锅<sup>25</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/angular混搭/" title="angular混搭">angular混搭<sup>33</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/box2djs方糖/" title="box2djs方糖">box2djs方糖<sup>34</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/cyclejs哈根达斯/" title="cyclejs哈根达斯">cyclejs哈根达斯<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/jQuery杂烩/" title="jQuery杂烩">jQuery杂烩<sup>3</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/js什锦/" title="js什锦">js什锦<sup>26</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/react沙拉/" title="react沙拉">react沙拉<sup>16</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/three-js奶茶/" title="three.js奶茶">three.js奶茶<sup>5</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/vue八宝粥/" title="vue八宝粥">vue八宝粥<sup>28</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/webpack宾治/" title="webpack宾治">webpack宾治<sup>9</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/web乱炖/" title="web乱炖">web乱炖<sup>2</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/前端满汉全席/" title="前端满汉全席">前端满汉全席<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/喵/" title="喵">喵<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/小程序双皮奶/" title="小程序双皮奶">小程序双皮奶<sup>21</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/工作这杯茶/" title="工作这杯茶">工作这杯茶<sup>4</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/应用巧克力盒/" title="应用巧克力盒">应用巧克力盒<sup>2</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/思想棉花糖/" title="思想棉花糖">思想棉花糖<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/柴米油盐工具集/" title="柴米油盐工具集">柴米油盐工具集<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/非前端钙片/" title="非前端钙片">非前端钙片<sup>7</sup></a>
			</li>
		
		</ul>
</div>


  
<div class="archiveslist">
	<p class="asidetitle">标签</p>
		<ul class="archive-list">
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/分享/" title="分享">分享<sup>44</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/原创部件/" title="原创部件">原创部件<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/心态/" title="心态">心态<sup>4</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/教程/" title="教程">教程<sup>65</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/晒猫/" title="晒猫">晒猫<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/笔记/" title="笔记">笔记<sup>121</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/算法/" title="算法">算法<sup>9</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/自制插件/" title="自制插件">自制插件<sup>2</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/逻辑实现/" title="逻辑实现">逻辑实现<sup>5</sup></a>
			</li>
		
		</ul>
</div>


    <div class="archiveslist">
    <p class="asidetitle"><a href="/archives">about</a></p>
      <ul class="archive-list">
      	<li class="archive-list-item">
      		<a>wangbeishan@163.com</a>
      		<a href="https://github.com/godbasin">github.com/godbasin</a>
      	</li>
      </ul>
  </div>

  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS 订阅</a>
</div>

</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<section class="info">
		<p> 即使梦想再小，却很伟大 ^_^ </p>
	</section>
	 
		<p class="copyright">Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/A-limon/pacman" target="_blank" title="Pacman">Pacman</a> © 2019 
		
		<a href="https://godbasin.github.io" target="_blank" title="被删">被删</a>
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else
    {
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      h  = $('article h2')
      ah = $('article h2'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  if(ah.length==0){
    t.css('display','none');
  }else{
    c.click(function(){
      ta.css('display', 'block').addClass('fadeIn');
    });
    o.click(function(){
      ta.css('display', 'none');
    });
    $(window).scroll(function(){
      ta.css("top",Math.max(140,320-$(this).scrollTop()));
    });
  };
});
</script>







  </body>
</html>
